package org.agamotto.cloud.template.core.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.agamotto.cloud.template.core.config.TemplateProperties;
import org.agamotto.cloud.template.exception.TemplateException;
import org.agamotto.cloud.template.service.GitService;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;

@Slf4j
@Service
public class GitServiceImpl implements GitService {

    private final File baseDir;

    public GitServiceImpl(TemplateProperties templateProperties) {
        baseDir = templateProperties.getFileDir();
        log.info("git文件存储目录:{}", baseDir);
    }


    public File updateRep(String url, String baseUrl) {
        Assert.hasText(url, "必须输入url");
        if (StringUtils.isEmpty(baseUrl)) {

            baseUrl = "https://gitee.com";
        }

        File repFile = new File(baseDir, url);
        if (repFile.exists()) {
            //已经存在，更新
            pullRepository(repFile);
        } else {
            cloneRepository(baseUrl + "/" + url + ".git", repFile);
        }
        return repFile;
    }


    private void pullRepository(File rep) {

        try (Git git = Git.open(rep)) {
            git.pull().call();

        } catch (IOException | GitAPIException e) {
            log.error("异常发生", e);
            deleteDir(rep);
            throw new TemplateException(e.getMessage());
        }

    }

    private void cloneRepository(String url, File rep) {
        log.info("克隆项目{}", url);
        try (Git git = Git.cloneRepository()
                .setURI(url)
                .setDirectory(rep).call()) {
            git.checkout();
        } catch (GitAPIException e) {
            log.error("异常发生", e);
            deleteDir(rep);
            throw new TemplateException(e.getMessage());
        }

    }

    private  boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children!=null && children.length>0) {
                for (String child : children) {
                    boolean success = deleteDir(new File(dir, child));
                    if (!success) {
                        return false;
                    }
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}
